#include <stdio.h>	
#include <string.h>

#include "evalsoc.h"

#include "evalsoc.h"
#include "evalsoc_spi.h"

void spi_case(dw_spi_regs_t * pspi){

	pspi->SSIENR = 0x0; // disable spi

	pspi->CTRLR0 = 0xf; //Transmit and Receive mode, CPOL =0, CPHA = 0 FIFO=16bit, normal mode

	pspi->SSIENR = 0x1; // enable spi

}


/**
 * @brief  spi初始化shiift loopback模式
 * @param  base_address: spi的基地址
 * @param  loopback_mode: 环回模式 Loopback_TESTING_MODE:环回模式，Loopback_NORMAL_MODE:正常模式
 */ 
void spi_init(uint32_t base_address,uint32_t loopback_mode){

	dw_spi_regs_t * pspi = (dw_spi_regs_t *)base_address;

	pspi->SSIENR = 0x0; // disable spi

	pspi->CTRLR0 = 0xf | loopback_mode; //Transmit and Receive mode, CPOL =0, CPHA = 0 FIFO=16bit, shift loopback
	pspi->BAUDR = 0x000000002;
	pspi->IMR = 0x0; // disable all interrupt
	pspi->DMACR = 0x3; //enable receive dma and transmit dma

	pspi->SSIENR = 0x1; // enable spi
		
	pspi->SER = 0x1; // enable ss 0x1-enable ss0, 0x2-enable ss1, 0x4-enable ss2, 0x8-enable ss3

}

/**
 * @brief  spi-slave模式
 * @param  base_address: spi的基地址
 * @param  loopback_mode: 环回模式 Loopback_TESTING_MODE:环回模式，Loopback_NORMAL_MODE:正常模式
 * 
 */
void spi_slave_init(uint32_t base_address,uint32_t loopback_mode){
	dw_spi_regs_t * pspi = (dw_spi_regs_t *)base_address;
	uint8_t rx_data[16];

	// Disable SPI before configuration
	pspi->SSIENR = 0x0;

	// Configure SPI slave mode
	pspi->CTRLR0 = 0x10002C7 | loopback_mode; // TMOD = 10 receive only, CPOL = 1, CPHA = 1, FIFO=8bit
	pspi->IMR = 0x0; // disable all interrupt
	

	// Enable SPI
	pspi->SSIENR = 0x1;

	printf("SPI Slave initialized. Waiting for data...\n");

	// Clear RX FIFO first
	while(pspi->SR & 0x8) {
		pspi->DR[0];  
	}

	while (1) {
		// Wait for data in RX FIFO
		while ((pspi->SR & 0x8) == 0x0) {
			__NOP();
		}
		
		// Read all available data
		int count = 0;
		while ((pspi->SR & 0x8) && count < 16) {  // Max 16 bytes per transaction
			rx_data[count++] = pspi->DR[0];

		}

		printf("Received data: ");
		for(int i = 0; i < count; i++){
			printf("%02X ", rx_data[i]);
		}
		printf("\n");

		if(count > 0) {
			printf("------------------------\n");
		}
	}
}
